<template>
  <div class="chat-container">
    <el-row :gutter="20">
      <el-col :span="16" :offset="4">
        <!-- 对话记录区域 -->
        <div class="chat-box" ref="chatBox">
          <div v-for="(message, index) in chatHistory" :key="index" 
               :class="['message-item', message.type === 'user' ? 'message-user' : 'message-assistant']">
            <el-avatar :size="40" :src="message.type === 'user' ? userAvatar : assistantAvatar"></el-avatar>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <el-input
            v-model="query"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题"
            @keyup.enter.native="handleEnter"
            :disabled="loading"
          >
          </el-input>
          <el-button type="primary" @click="handleSearch" :loading="loading" 
                     :disabled="!query.trim()">
            发送
          </el-button>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar">
          <el-button-group>
            <el-button type="text" @click="drawerVisible = true">
              <i class="el-icon-time"></i> 历史记录
            </el-button>
            <el-button type="text" @click="clearChat" :disabled="!chatHistory.length">
              <i class="el-icon-delete"></i> 清空对话
            </el-button>
          </el-button-group>
        </div>

        <!-- 历史记录抽屉 -->
        <el-drawer
    title="历史记录"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="30%"
  >
          <div class="history-list">
            <div class="context-tip">
              <i class="el-icon-info"></i> 当前支持最多{{ maxHistoryLength }}轮上下文对话
            </div>
            <el-empty v-if="!historySessions.length" description="暂无历史记录"></el-empty>
            <div v-else v-for="(session, index) in historySessions" :key="index" 
                 class="history-item" @click="loadHistorySession(session)">
              <span class="history-title">{{ session.title }}</span>
              <span class="history-time">{{ session.time }}</span>
            </div>
          </div>
        </el-drawer>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'ChatInterface',
  data() {
    return {
      query: '',
      chatHistory: [],
      loading: false,
      drawerVisible: false,
      historySessions: [],
      knowledgeBase: null,
      userAvatar: require('@/assets/deepseekSearchImg/nezha.jpg'),
      assistantAvatar: require('@/assets/deepseekSearchImg/aobing.jpg'),
      maxHistoryLength: 10, // 添加上下文长度限制
    }
  },

  async created() {
    await this.initKnowledgeBase()
    this.loadHistoryFromLocalStorage()
  },

  methods: {
    async initKnowledgeBase() {
      try {
        const response = await this.$request.get('/tpa/api/view_data/')
        this.knowledgeBase = response.data
      } catch (error) {
        this.$message.error('获取知识库失败')
        console.error(error)
      }
    },

    handleEnter(e) {
      if (e.shiftKey) return
      e.preventDefault()
      this.handleSearch()
    },
    
    async handleSearch() {
      if (!this.query.trim() || this.loading) return

      this.loading = true
      const userQuery = this.query.trim()
      this.addMessage(userQuery, 'user')
      this.query = ''

      try {
        const response = await this.$request.post(
          '/ds/deepseek_search/',
          { query: userQuery },
          { timeout: 60000 }
        )

        // 修复响应数据处理
        if (response.result) {
          this.addMessage(response.result, 'assistant')
          this.saveToHistory()
          // 添加上下文计数提示
          if (this.chatHistory.length >= this.maxHistoryLength) {
            this.$message.warning('上下文对话长度已达限制，建议开启新对话')
          }
        } else {
          throw new Error('Invalid response format')
        }
      } catch (error) {
        // 增强错误处理
        const errorDetail = error.response?.data?.error || error.message
        const errorMessage = `请求失败: ${errorDetail}`
        this.addMessage(errorMessage, 'error')
        this.$message.error(errorMessage)
      } finally {
        this.loading = false; // 确保无论请求成功还是失败，loading 都会被重置
      }
    },

    formatMessage(content) {
      // 简单的文本格式化，可以根据需要扩展
      return content.replace(/\n/g, '<br>')
    },

    addMessage(content, type) {
      this.chatHistory.push({
        content,
        type,
        time: new Date().toLocaleTimeString()
      })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox
        chatBox.scrollTop = chatBox.scrollHeight
      })
    },

    saveToHistory() {
      const session = {
        title: this.chatHistory[0].content.substring(0, 20) + '...',
        time: new Date().toLocaleString(),
        messages: [...this.chatHistory]
      }
      this.historySessions.unshift(session)
      localStorage.setItem('chatHistory', JSON.stringify(this.historySessions.slice(0, 20))) // 只保存最近20条
    },

    loadHistoryFromLocalStorage() {
      try {
        const history = localStorage.getItem('chatHistory')
        if (history) {
          this.historySessions = JSON.parse(history)
        }
      } catch (error) {
        console.error('Failed to load history:', error)
        localStorage.removeItem('chatHistory')
      }
    },

    loadHistorySession(session) {
      this.chatHistory = [...session.messages]
      this.drawerVisible = false
      this.scrollToBottom()
    },

    clearChat() {
      this.$confirm('确定要清空当前对话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.chatHistory = []
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.chat-container {
  padding: 20px;
  height: 100vh;
  background-color: #f5f7fa;
}

.chat-box {
  height: calc(100vh - 250px);
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message-user {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
  margin: 0 12px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  background: #f4f4f5;
  line-height: 1.5;
}

.message-user .message-text {
  background: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  text-align: right;
}

.input-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.input-area .el-button {
  align-self: flex-end;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
}

.history-list {
  padding: 10px;
}

.history-item {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-title {
  font-weight: 500;
  color: #303133;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

/* 添加错误消息样式 */
.message-error .message-text {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

/* 添加上下文计数提示 */
.context-tip {
  padding: 10px;
  background: #f4f4f5;
  color: #909399;
  font-size: 12px;
  border-radius: 4px;
  margin-bottom: 10px;
}

/* 优化消息气泡样式 */
.message-text {
  position: relative;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message-assistant .message-text {
  background: #f6ffed;
  border: 1px solid #e1f3d8;
}
</style>